package model.entity.brain;

import model.entity.BasicEntity;
import model.map.Direction;
import model.map.GameMap;
import model.map.HexLocationProjection;
import model.map.Location;
import model.map.World;
import utilities.*;

public class BehaveState extends PetState implements Archiveable {
	String name;
	public BehaveState(){
		name = "Behave";
	}
	
	public String getName(){
		return name;
	}
	
	/**
	 * since the npc is behaving, it just follows the avatar
	 */
	public Direction getNextMove(BasicEntity npc, Location avatarLoc, GameMap gm){
		HexLocationProjection hlp = new HexLocationProjection();
		Location tempLoc;
		Direction bestDir = Direction.SW;
		Direction dir = Direction.SW;
		int minDist = 999;
		
		// cycle through each direction
		for(int i=0; i < 10; i ++){
			// only 6 possible directions so skip 4,5,6
			if( i == 4)
				i = 7;
			
			// convert the number chosen to a direction
			switch(i){
				case 1: dir = Direction.SW; break;
				case 2: dir = Direction.S; break;
				case 3: dir = Direction.SE; break;
				case 7: dir = Direction.NW; break;
				case 8: dir = Direction.N; break;
				case 9: dir = Direction.NE; break;
			}
			
			// find the next block in that direction
			tempLoc = hlp.projectLocation(npc.getLocation(), dir);
			
			// only store direction with shortest dist but not colliding with avatar
			avatarLoc = World.getInstance().getPlayer().getLocation();
			int dist = distanceCalculator(tempLoc, avatarLoc);
			// dont move into avatar so > 0 but move towards it or around it
			if(dist > 0 && dist < minDist){
				bestDir = dir;
				minDist = dist;
			}
		}
		return bestDir;
	}

	/**
	 * find distances between two locations
	 * @param loc1
	 * @param loc2
	 * @return
	 */
	private int distanceCalculator(Location loc1, Location loc2){
		int xdist = loc1.getX() - loc2.getX();
		int ydist = loc1.getY() - loc2.getY();
		if(xdist < 0){
			xdist = -xdist;
		}
		if(ydist < 0){
			ydist = -ydist;
		}
		return xdist+ydist;
	}
	
	public Archive save() {
		Archive archive = super.save();
		
//		archive.putAttribute("name", this.name);
		
		return archive;
	}
	
	public void load(Archive archive) {
		super.load(archive);
		
//		this.name = archive.getAttribute("name");
	}
		
}